//
//  ErrorsExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/5/31.
//

import Foundation
import UIKit

class ErrorsExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "Error 类型判断", description: "使用 switch 判断并获取关联值", action: errorType),
    .init(title: "NSInternalInconsistencyException", description: "子线程操作 UI", action: throwsNSInternalInconsistencyException),
  ]
}

private func throwsNSInternalInconsistencyException() {
  let label = UILabel()
  DispatchQueue.global(qos: .background).async {
    label.text = "更新后的文本"
  }
}

public enum AccountError: Error, LocalizedError {
  case apiError(code: Int, message: String)
  case loginFailed
}

enum OAuthError: Error, LocalizedError {
  case unwrappedError(String)
}

fileprivate enum MoyaError: Error {
  case underlying(Error)
}

private func errorType() {
  print(AccountError.apiError(code: 404, message: "接口不存在").toast) // 1.
  print(AccountError.apiError(code: 401, message: "认证失败").toast) // 2.
  print(AccountError.loginFailed.toast) // 3.
  print(OAuthError.unwrappedError("data is nil").toast) // default.
  
  print(MoyaError.underlying(AccountError.apiError(code: 1995, message: "database access error.")).toast) // default.
}

private func getErrorDescription(_ error: Error) -> String {
  print("🔴", error)
  switch error {
  case let AccountError.apiError(code, message) where code == 404:
    return "1. let where code == 404 code: \(code), message: \(message)"
  case let AccountError.apiError(code, message):
    return "2. let code: \(code), message: \(message)"
  case is AccountError:
    return "3. is AccountError error: \(error.localizedDescription)"
  case let MoyaError.underlying(underlyingError):
    return getErrorDescription(underlyingError)
  default:
    return "default."
  }
}

extension Error {
  public var toast: String {
    return getErrorDescription(self)
  }
}
